package com.travel.sso.service.impl;


import com.travel.sso.dao.UserDAO;
import com.travel.sso.service.UserService;
import com.travel.sso.util.TravelResult;
import common.pojo.User;
import common.util.JedisClient;
import common.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private JedisClient jedisClient;

    @Override
    public TravelResult doLogin(String email, String password) {
        TravelResult travelResult = new TravelResult();
        User user = userDAO.getUserEmail(email);
        if (user == null || !user.getPassword().equals(password)) {
            return null;
        }
        try {
            String token = System.currentTimeMillis() + "_" + user.getId();
            jedisClient.set("USER_SESSION:" + token, JsonUtil.getJSON(user));
            travelResult.setData(token);
            travelResult.setStatus(true);
            return travelResult;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User getUserInfo(String token) {
        String json = jedisClient.get("USER_SESSION:" + token);
        if (json == null) {
            return null;
        }
        try {
            return (User) JsonUtil.getObj(json, User.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
